﻿using System;
using System.Web;
using System.Web.UI.WebControls;
using DBProvider;
using DBProvider.Providers;
using System.Text;
using System.IO;

namespace HealthCommunity.Controls
{
	public partial class UCMaterialNewest : System.Web.UI.UserControl
	{
		private IMaterialProvider _MaterialProvider;

		protected void Page_Load(object sender, EventArgs e)
		{
			//if(!IsPostBack)
			{
				BindMaterial();
			}
		}

		protected void rptMaterial_ItemDataBound(object sender, RepeaterItemEventArgs e)
		{
			var lbtnDownload = e.Item.FindControl("lbtnDownload") as LinkButton;
			var hlMaterial = e.Item.FindControl("hlMaterial") as HyperLink;
			var dataItem = e.Item.DataItem as Material;

			if(dataItem != null)
			{
				lbtnDownload.CommandArgument = dataItem.MaterialID.ToString();

				if(dataItem.MaterialName.Length > 16)
				{
					hlMaterial.Text = dataItem.MaterialName.Substring(0, 16) + "...";
					hlMaterial.ToolTip = dataItem.MaterialName;
				}
				else
				{
					hlMaterial.Text = dataItem.MaterialName;
					hlMaterial.ToolTip = dataItem.MaterialName;
				}

				if(!string.IsNullOrEmpty(dataItem.MaterialPath))
				{
					var p = dataItem.MaterialPath.Split('\\');
					var key = string.Empty;
					if(p != null && p.Length > 0)
					{
						key = p[p.Length - 1];
					}
					hlMaterial.NavigateUrl = "~/DocumentViewer.aspx?key=" + key;
				}
			}
		}

		protected void rptMaterial_ItemCommand(object source, RepeaterCommandEventArgs e)
		{
			if(e.CommandName.Equals("download"))
			{
				var materialID = int.Parse(e.CommandArgument.ToString());

				if(_MaterialProvider == null)
				{
					_MaterialProvider = new MaterialProvider();
				}

				var theMaterial = _MaterialProvider.GetMaterial(materialID);

				if(theMaterial != null)
				{
					if(DownloadMaterial(theMaterial))
					{
						var user = SiteContext.Current.CurrentUser;

						var userProvider = new UserProvider();
						user.Credits -= theMaterial.DownloadRequiedScore.GetValueOrDefault(0);

						if(userProvider.UpdateUser(user, false))
						{
							if(_MaterialProvider == null)
							{
								_MaterialProvider = new MaterialProvider();
							}

							theMaterial.DowloadCount = theMaterial.DowloadCount.GetValueOrDefault(0) + 1;

							_MaterialProvider.UpdateMaterial(theMaterial);
						}

						Response.End();
					}
				}
			}

		}

		private void BindMaterial()
		{
			if(_MaterialProvider == null)
			{
				_MaterialProvider = new MaterialProvider();
			}

			var user = SiteContext.Current.CurrentUser;

			if(user != null && user.Role != null && user.Role.RoleName.Equals("admin"))
			{
				var drugStore = SiteContext.Current.CurrentDrugStore;

				if(drugStore != null)
				{
					rptMaterial.DataSource = _MaterialProvider.GetNewMaterials(12, drugStore.DrugStoreID);
					rptMaterial.DataBind();
				}
			}
			else
			{
				if(user != null && user.DrugStoreID.GetValueOrDefault(0) > 0)
				{
					rptMaterial.DataSource = _MaterialProvider.GetNewMaterials(12, user.DrugStoreID.GetValueOrDefault(0), user.UserID);
					rptMaterial.DataBind();
				}
			}
		}

		private bool DownloadMaterial(Material theMaterial)
		{
			if(theMaterial != null)
			{
				if(IsEligibleUser(theMaterial))
				{
					var mtrPathPart = theMaterial.MaterialPath.Split('\\');
					var fileName = mtrPathPart[mtrPathPart.Length - 1];
					var newFileName = string.Format("{0}.{1}", theMaterial.MaterialName, fileName.Split('.')[1]);
					var filePath = Server.MapPath("~/Document");
					FileInfo fileInfo = new FileInfo(theMaterial.MaterialPath);

					if(fileInfo.Exists)
					{
						FileStream fs = new FileStream(theMaterial.MaterialPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
						BinaryReader br = new BinaryReader(fs);

						try
						{
							long startBytes = 0;
							string lastUpdateTiemStamp = File.GetLastWriteTimeUtc(filePath).ToString("r");
							string _EncodedData = HttpUtility.UrlEncode(newFileName, Encoding.UTF8) + lastUpdateTiemStamp;

							Response.Clear();
							Response.Buffer = false;
							Response.AddHeader("Accept-Ranges", "bytes");
							Response.AppendHeader("ETag", "\"" + _EncodedData + "\"");
							Response.AppendHeader("Last-Modified", lastUpdateTiemStamp);
							Response.ContentType = "application/octet-stream";
							Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(newFileName, System.Text.Encoding.UTF8));
							Response.AddHeader("Content-Length", (fileInfo.Length - startBytes).ToString());
							Response.AddHeader("Connection", "Keep-Alive");
							Response.ContentEncoding = Encoding.UTF8;

							//Send data
							br.BaseStream.Seek(startBytes, SeekOrigin.Begin);

							//Dividing the data in 1024 bytes package
							int maxCount = (int)Math.Ceiling((fileInfo.Length - startBytes + 0.0) / 1024);

							//Download in block of 1024 bytes
							int i;
							for(i = 0; i < maxCount && Response.IsClientConnected; i++)
							{
								Response.BinaryWrite(br.ReadBytes(1024));
								Response.Flush();
							}
							//if blocks transfered not equals total number of blocks
							if(i < maxCount)
							{
								return false;
							}

							return true;
						}
						catch
						{
							return false;
						}
						finally
						{
							br.Close();
							fs.Close();
						}
					}
					else
					{
						return false;
					}
				}
				else
				{
					return false;
				}
			}
			else
			{
				return false;
			}
		}

		private bool IsEligibleUser(Material theMaterial)
		{
			var result = false;

			var user = SiteContext.Current.CurrentUser;

			if(user != null)
			{
				result = user.Credits >= theMaterial.DownloadRequiedScore.GetValueOrDefault(0);
			}

			return result;
		}
	}
}